import React from 'react'
import './index.css'
// import ReactDOM from 'react-dom'

const Row = 3; // 每行个数，总个数为 Row*Row

var Square = function(props) {
    return (
        <button className="square" onClick={props.onClick}>
            {props.value}
        </button>
    );
} 

class Board extends React.Component {
    constructor() {
        super()
        this.state = {
            squares: Array(Row * Row).fill(null),
            isX : true
        }
    }

    handleClick(i) {
        const squares = this.state.squares.slice();
        squares[i] = this.state.isX ? 'X' : 'O';
        this.setState({squares: squares});
        const isX = this.state.isX;
        this.setState({isX: !isX});
    }

    renderSquare(squareRow, that) {
        // 循环填充每个棋子
        var listBtn = (rowNum, num) => {
            const btns = []
            for(var i=0; i<num; i++) {
                const j = num * rowNum + i
                btns.push(
                    <Square key={j} value={that.state.squares[j]} onClick={() => that.handleClick(j)}/>
                )
            }
            return btns;
        }
        // 循环填充每行
        var listRow = (rowNum, squareRow) => {
            const btnRow = [];
            for(var r=0; r<rowNum; r++) {
                btnRow.push(
                    <div key={r} className='boardrow'>{listBtn(r, squareRow)}</div>
                )
            }
            return btnRow;
        }

        return (
            <div>{listRow(Row, squareRow)}</div>
        );
    }

    render() {
        const status = 'Now player is ' + (this.state.isX ? 'X' : 'O');

        return (
            <div className='board'> 
                <div className='status'>{status}</div>
                {this.renderSquare(Row, this)}
            </div>
        );
    }
}

export default Board;
